
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Transactions;

namespace CrmDocman.DataCore {
    /// <summary>
    /// This object will hold the db connection of the application.
    /// </summary>
    public class ConnectionWrapper {

        private String m_connectionString = null;

        // connection
        private DbConnection m_connection = null;

        // transaction
        private IDbTransaction m_transaction = null;

        public ConnectionWrapper(string connectionString) {
            m_connectionString = connectionString;
        }
        public void OpenConnection() {
            OpenConnection(false);
        }

        public void OpenConnection(bool autoHandleTransaction) {
            if (m_connection == null) {
                m_connection = new SqlConnection();
                m_connection.ConnectionString = m_connectionString;
            }
            if (m_connection.State == ConnectionState.Closed) {
                m_connection.Open();
            }
            if (autoHandleTransaction) {
                m_transaction = m_connection.BeginTransaction();
            }
        }

        public void CloseConnection() {
            CloseConnection(false);
        }

        public void CloseConnection(bool hasError) {
            // close transaction
            if (m_transaction != null) {
                if (!hasError) {
                    m_transaction.Commit();
                } else {
                    m_transaction.Rollback();
                }                
                m_transaction.Dispose();
            } 

            // close connection
            try {
                if(m_connection.State == ConnectionState.Open) {
                    m_connection.Close();
                }
            } catch {
            }
        }


        public ConnectionWrapper Copy() {            
            return new ConnectionWrapper(this.ConnectionString);
        }

        public String ConnectionString {
            get {
                return m_connectionString;
            }
            set {
                m_connectionString = value;
            }
        }

        public DbConnection Connection {
            get {
                return m_connection;
            }
            set {
                m_connection = value;
            }
        }

        public IDbTransaction Transaction {
            get {
                return m_transaction;
            }
            set {
                m_transaction = value;
            }
        }
    }
}
